// pages/ai/creationHistory/index.js
// const {
//   TickSystem
// } = require('XrFrame/systems')
const {
  GPTSHIXIANJIA
} = require('../../../api/config/config')
const {
  aiCreationApi
} = require('../../../api/index')
const app = getApp()

Page({
  data: {
    arr: [1, 2, 3, 5],
    listLoadStatus: 0,
    pageLoading: false,
    list: [], //总条数
    listYesterday: [], //昨天数据
    listWeek: [], //一周
    listDay: [],
    uniqueArray: [], //一周汇总
    startTime: '',
    endTime: '',
    timeType: 0, //0：今天 1:昨天 2：一周内
    TaskIdList: [],
    creativeUnfinishednewArray: [],
    currentDay: new Date().getDate(),
    IMGBASEURL: app.globalData.IMGBASEURL,
    showRequest: false,
    loadOrNot: null,
    clearMergedItems: false,
    completeTheRequest: false, //全部是否请求完毕
    footerTitel: '没有更多了',
    recordedNumber: null, //记录上一次生图数量
  },
  listPagination: {
    index: 0,
    num: 15,
  },
  /**
   * 获取历史数据
   */
  async loadData(fresh = false) {
    let _this = this
    this.setData({
      listLoadStatus: 1,
    });
    const pageSize = this.listPagination.num;
    let pageIndex = this.listPagination.index + 1;
    if (fresh) {
      pageIndex = 1;
    }
    try {
      const res = await aiCreationApi.creationiHstory({
        "PageIndex": pageIndex, //第几页
        "pageCount": pageSize, //每页数据量
        "userId": wx.getStorageSync('userInfo').UserId,
        "orderCreationTime": false,
        "creationTypeStr": "0",
        "isExcludeTimeDate": true,
        "startTime": _this.TimeHorizon(_this.data.timeType).startTime,
        "endTime": _this.TimeHorizon(_this.data.timeType).endTime,
      })
      this.setData({
        pageLoading: false,
      });
      wx.stopPullDownRefresh();
      const nextList = res.items
      this.setData({
        loadOrNot: true,
        footerTitel: '没有更多了'
      })

      if (res.totalPages >= pageIndex && this.data.timeType === 0) {

        // 今天的数据
        this.setData({
          listDay: fresh ? nextList : this.data.listDay.concat(nextList),
          loadOrNot: false,
        })

        let accordWithDataList = this.data.listDay.length === res.totalCount //当前数据是否请求完毕
        this.setData({
          listLoadStatus: accordWithDataList ? 2 : 0
        })
      }

      if (res.totalPages >= pageIndex && this.data.timeType === 1) {

        // 昨天的数据
        this.setData({
          listYesterday: fresh ? nextList : this.data.listYesterday.concat(nextList),
          loadOrNot: false,
        })

        let accordWithListYesterday = this.data.listYesterday.length === res.totalCount //当前数据是否请求完毕
        this.setData({
          listLoadStatus: accordWithListYesterday ? 2 : 0,
        })
      }

      if (res.totalPages >= pageIndex && this.data.timeType === 2) {
        // 一周内的数据
        this.setData({
          listWeek: fresh ? nextList : this.data.listWeek.concat(nextList),
          loadOrNot: false,
          clearMergedItems: false,
        })
        let accordWithListWeek = this.data.listWeek.length === res.totalCount //当前数据是否请求完毕
        this.setData({
          listLoadStatus: accordWithListWeek ? 2 : 0,
        })
      }

      this.setData({
        list: [...this.data.listDay, ...this.data.listYesterday, ...this.data.listWeek],
      });
      //当所有时间段数据合并不满足15条，则会将文字隐藏
      if (this.data.list.length < 15) {
        setTimeout(() => {
          this.setData({
            footerTitel: ''
          })
        }, 1000);
      }
      if (this.data.timeType === 2 && nextList.length === 0) {
        this.setData({
          listLoadStatus: 2,
          completeTheRequest: true, //全部数据请求完毕 
        })
        return
      }
      this.listPagination.index = pageIndex;
      this.listPagination.num = pageSize;

      //处理数据添加
      if ((nextList.length <= 0) || (this.data.list.length < 15) || ((this.data.listLoadStatus === 2) && this.data.timeType !== 2)) {
        let currentTimeType = this.data.timeType
        currentTimeType++
        this.setData({
          timeType: currentTimeType,
        })
      }
      if (((nextList.length <= 0) || (this.data.list.length < 15)) && this.data.timeType < 3) {
        this.loadData(true)
      }

    } catch (error) {
      this.setData({
        listLoadStatus: 3
      });
    }
  },

  /**
   * 时间范围
   */
  TimeHorizon(tyep) {
    let now = new Date();
    let current = new Date(now);
    switch (tyep) {
      case 0:
        // 计算今天的时间  
        let day = new Date(current);
        day.setDate(current.getDate());
        return {
          startTime: this.dateTimeString(current) + ' ' + '00' + ':' + '00' + ':' + '00',
            endTime: this.dateTimeString(day) + ' ' + 23 + ':' + '59' + ':' + '59'
        }
        case 1:
          // 计算昨天的时间  
          let yesterday = new Date(current);
          yesterday.setDate(current.getDate() - 1);
          return {
            startTime: this.dateTimeString(yesterday) + ' ' + '00' + ':' + '00' + ':' + '00',
              endTime: this.dateTimeString(yesterday) + ' ' + 23 + ':' + '59' + ':' + '59'
          }
          case 2:
            var currentDate = new Date();
            currentDate.setDate(currentDate.getDate() - 8);
            var futureDate = new Date(currentDate);
            var formattedDate = futureDate.getFullYear() + '-' +
              ('0' + (futureDate.getMonth() + 1)).slice(-2) + '-' +
              ('0' + futureDate.getDate()).slice(-2);
            let weekEndTime = this.getDateAfter7Days(formattedDate)

            return {
              startTime: formattedDate + ' ' + '00' + ':' + '00' + ':' + '00',
                endTime: weekEndTime + ' ' + 23 + ':' + '59' + ':' + '59'
            }
    }
  },
  //标准时间
  dateTimeString(valueTime) {
    // 解析日期时间字符串为 Date 对象  
    let dateTime = new Date(valueTime);
    // 分别获取年、月、日、时、分、秒  
    let year = dateTime.getFullYear();
    let month = dateTime.getMonth() + 1; // getMonth() 返回的月份是从 0 开始的，所以需要加 1  
    let date = dateTime.getDate();
    let hours = dateTime.getHours();
    let minutes = dateTime.getMinutes();
    let seconds = dateTime.getSeconds();
    // 如果月份、日期、小时、分钟、秒数小于 10，前面补 0  
    month = month < 10 ? '0' + month : month;
    date = date < 10 ? '0' + date : date;
    hours = hours < 10 ? '0' + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    // 拼接成年月日时分秒的格式  
    let formattedDateTime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
    return year + '-' + month + '-' + date
  },
  //计算往后的7天时间
  getDateAfter7Days(dateString) {
    // 解析输入的日期字符串  
    const dateParts = dateString.split('-');
    const year = parseInt(dateParts[0], 10);
    const month = parseInt(dateParts[1], 10) - 1; // 月份从0开始  
    const day = parseInt(dateParts[2], 10);

    // 创建一个Date对象  
    const date = new Date(year, month, day);

    // 将日期往后推7天  
    date.setDate(date.getDate() + 6);

    // 格式化新的日期为"YYYY-MM-DD"格式  
    const newYear = date.getFullYear();
    const newMonth = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以需要加1并补零  
    const newDay = date.getDate().toString().padStart(2, '0'); // 补零  

    // 返回新的日期字符串  
    return `${newYear}-${newMonth}-${newDay}`;
  },

  //下拉刷新
  onPullDownRefresh() {
    this.setData({
      pageLoading: true,
      clearMergedItems: true,
      timeType: 0,
      listLoadStatus: 1,
      listDay: [],
      listYesterday: [],
      listWeek: [],
      creativeUnfinishednewArray: [],
    });
    this.loadData(true)
    this.theDrawingIsNotComplete()
  },
  // 触底事件
  onReachBottom() {
    if (this.data.timeType <= 2 && !this.data.completeTheRequest) {
      this.loadData();
    }
  },
  onReTry() {
    this.loadData();
  },

  /**
   * 去创作完成页
   */
  toComplete(e) {
    wx.removeStorageSync('styleStr')
    wx.setStorageSync('shareImgList', {
      imgList: e.currentTarget.dataset.item.images
    })
    wx.navigateTo({
      url: '/pages/ai/creationComplete/index?isHistory=1',
    })
  },

  /**
   * 出图未完成的历史历史记录
   */
  theDrawingIsNotComplete() {
    // if (this.data.showRequest) {
    aiCreationApi.getTheDrawingIsNotComplete({}).then(res => {
      let photographNumber = res.result != null ? res.result : []
      this.setData({
        recordedNumber: photographNumber,
        showRequest: res.result != null ? false : true
      })
      // if (!res.result) {
      //   this.loadData(true) //刷新数据
      //   return
      // }
      // if (this.data.recordedNumber != res.result.length) {
      //   this.loadData(true) //刷新数据
      // }
      let totalBatchSize = res.result.reduce((sum, item) => sum + item.batchSize, 0);
      let newArray = new Array(totalBatchSize);
      for (let i = 0; i < totalBatchSize; i++) {
        newArray[i] = null;
      }
      this.setData({
        creativeUnfinishednewArray: newArray,
      })
      // if (res.result.length <= 0) {
      // }

      // this.onPullDownRefresh()
      // wx.showToast({
      //   title: `创作成功`,
      //   icon: 'none',
      //   duration: 2000
      // })
    }).catch(err => {
      this.setData({
        showRequest: false
      })
    })
    // } else {
    //   this.setData({
    //     creativeUnfinishednewArray: [],
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    this.startPolling()
    this.loadData()

  },
  // 开始轮询出图结果  
  startPolling() {
    this.pollIntervalId = setInterval(this.theDrawingIsNotComplete, 5000);
  },

  // 停止轮询的函数  
  stopPolling() {
    // 清除轮询定时器  
    clearInterval(this.pollIntervalId);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.theDrawingIsNotComplete()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.stopPolling(); // 页面卸载时停止轮询  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopPolling(); // 页面卸载时停止轮询  
  },
})